<template>
  <div>
    <!-- 搜索 -->
    <!-- 预授权级别维护 -->
    <TopFilter ref="topFilter" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="120" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <FilterTable ref="table" :columns="columns" :params="fetchParams" :fetchapi="fetchapi" :datakey="'records'" :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectChange" :is-select-column="false" columnsRef="AuthApplicationlgr">
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>
        <multiuse-button size="small" type="primary" :click="goDownLoadFile.bind()">下载</multiuse-button>
        <multiuse-button size="small" type="primary" :loading="exportLoading" :click="goExportFile.bind()">导出模板</multiuse-button>
        <multiuse-button size="small" type="primary" icon="el-icon-upload" :click="goImportFile.bind()">数据导入</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog width="30%" :visible.sync="visibleEdit" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 70px)', overflow: 'auto', paddingBottom: '70px' }">
      <diaLogForm :row="rowData" :currentUserInfo="currentUserInfo" :type="type" @close="closeDialog" @saveDialog="saveDialog" />
    </BaseDialog>
    <BaseDialog :visible.sync="showImport" :closable="false" icon="el-icon-upload" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="saveExcel()" :url='`${uploadUrl}/api/cms_claimfac/rpPart/importExcel`' :hideErrorMsg='true' />
      <!-- <importExcel @close="showImport = false" @importclose="saveExcel()" :url='`http://localhost:8080/chengbowen/rpPart/importExcel`' /> -->
    </BaseDialog>
  </div>
</template>

<script>
import { getListByPage, deletePart } from '@/api/claim/dealer/AuthMaintenance';
import { factoryEmployeeSearch } from '@/api/common/auth/dealerStaff';
import diaLogForm from './diaLogForm.vue';
import { downloadModel, exporturl } from '@/api/claim/factory/DealerPartManageHourMaintain';
import { exportExcelFile } from '@/utils/index';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';
import { getListPart, exportPart, exportPartModel, selectrpPartById } from '@/api/claim/dealer/AuthMaintenance';
import { dictionary } from '@/utils/dictMixin';
import config from '@/assets/js/config';
import { getUserId } from '@/assets/js/auth';
export default {
  name: "index",
  mixins: [dictionary],
  components: {
    diaLogForm,
    importExcel
  },
  data() {
    return {
      topFilterInit: this.topFilterInitFun(),
      fetchParams: { xhrAbort: false }, //ipa 接口
      columns: this.creatHeader(),
      selectedRows: [], //选中
      collapse: true,
      fetchapi: getListPart,
      visibleEdit: false,
      rowData: {},
      dialogTitle: '',
      type: '',
      exportLoading: false,//导出模板加载中..
      showImport: false,//导入
      uploadUrl: config.uploadUrl,
      currentUserInfo: {
        createdById: '',
        updatedById: getUserId(),
      }
    }
  },
  created() { },
  methods: {
    saveExcel() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    //下载
    async goDownLoadFile() {
      // let json = Object.assign({}, { CODE: 'CODE_00000123' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode === 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      this.fetchParams = { 'partCode': '', 'partName': '', ...this.fetchParams }
      for (let item in this.fetchParams) {
        if (item != 'xhrAbort') {
          this.fetchParams[item] = this.fetchParams[item] ? this.fetchParams[item] : '';
        }
      }
      this.exportLoading = true;

      exportPart(this.fetchParams).then((res) => {
        console.log(res.data)
        exportExcelFile(res.data, '预授权备件查询');
        this.exportLoading = false;
      });
    },
    //导出模板
    goExportFile() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true;
        exportPartModel().then(res => {
          exportExcelFile(res.data, '预授权备件模板');
          this.exportLoading = false;
        });
      });
    },
    //数据导入
    goImportFile() {
      this.showImport = true;
    },
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'INPUT', label: '备件代码', fieldName: 'partCode', placeholder: '请输入...', initialValue: '' },
        { type: 'INPUT', label: '备件名称', fieldName: 'partName', placeholder: '请输入...', initialValue: '' },
        { type: 'SELECT', label: '预授权类型', fieldName: 'authType', placeholder: '请选择预授权类型...', itemList: this.createDictList('5508'), initialValue: '' },
      ];
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: props => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.edit(props.row)} >编辑 </multiuse-button>
                <el-button size="mini" type="text" onClick={() => this.deleteItem(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        { title: '备件代码', dataIndex: 'partCode', sorter: true },
        { title: '备件名称', dataIndex: 'partName', sorter: true },
        { title: '授权级别', dataIndex: 'name', sorter: true },
        {
          title: '预授权类型', dataIndex: 'authType',
          filterItems: this.createDictList('5508'),
          dictItems: this.createDictList('5508'),
          render: props => {
            return <span>{this.createDictText(props.row.authType, '5508')}</span>;
          }
        },
        { title: '创建人', dataIndex: 'createdBy', sorter: true },
        { title: '创建时间', dataIndex: 'createdAt', sorter: true, dateFormat: 'yyyy-MM-dd HH:mm:ss' },
        { title: '修改人', dataIndex: 'updatedBy', sorter: true },
        { title: '修改时间', dataIndex: 'updatedAt', sorter: true, dateFormat: 'yyyy-MM-dd HH:mm:ss' },
      ];
    },
    //选中行
    selectChange(rows) {
      this.selectedRows = rows;
    },
    edit(val) {
      this.rowData = val;
      this.visibleEdit = true;
      this.dialogTitle = '预授权编辑';
      this.type = 'edit';

      selectrpPartById(val.ptId).then((res) => {
        console.log(res);
        if (res.resultCode === 200) {
          this.currentUserInfo.createdById = res.data.createdBy;
        }
      });

    },
    add() {
      this.rowData = {}
      this.dialogTitle = '预授权新增';
      this.visibleEdit = true;
      this.type = 'add'
    },
    deleteItem(val) {
      // let array = [val];
      // this.$refs.table.EXECUTE_DELETE(array);
      // this.$notify({
      //   title: '成功',
      //   message: '删除成功',
      //   type: 'success'
      // });
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deletePart(val.ptId)
        if (res.errMsg) {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '删除失败!' });
        } else {
          this.$notify.success({ title: '提示信息', message: '删除成功!' });
          // 重新加载
          this.fetchParams = { ...this.fetchParams };
        }
      }).catch(() => {
        // this.$notify.info({title: '提示信息',message:'已取消删除'});
      });
    },
    async closeDialog() {
      this.visibleEdit = false;
      const [err, data] = await this.$refs.topFilter.GET_FORM_DATA();
      this.fetchParams = { ...this.fetchParams, ...data };
    },
    async saveDialog() {
      const [err, data] = await this.$refs.topFilter.GET_FORM_DATA();
      this.fetchParams = { ...this.fetchParams, ...data };
    }
  }
}
</script>

<style scoped>
</style>
